package com.example.myshopping3.controller;

import com.example.myshopping3.commons.CurUser;
import com.example.myshopping3.exceptions.BadPasswordException;
import com.example.myshopping3.exceptions.LockedException;
import com.example.myshopping3.exceptions.UserNameNotFoundException;
import com.example.myshopping3.model.LoginParam;
import com.example.myshopping3.model.Result;
import com.example.myshopping3.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public Result login(@RequestBody LoginParam loginParam, HttpSession session){
        try {
            CurUser curUser = userService.login(loginParam.getUserName(), loginParam.getUserPassword());
            session.setAttribute("curUser",curUser);
            return Result.success("登录成功",curUser);
        } catch (BadPasswordException e) {
            e.printStackTrace();
            return Result.failt(401,e.getMessage(),null);
        } catch (LockedException e) {
            e.printStackTrace();
            return Result.failt(401,e.getMessage(),null);
        } catch (UserNameNotFoundException e) {
            e.printStackTrace();
            return Result.failt(401,e.getMessage(),null);
        }
    }

    @DeleteMapping("/exit")
    public Result exit(HttpSession session)
    {
        session.removeAttribute("curUser");
        return Result.success("退出成功", null);
    }
}
